﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlogEngine.Core;
using System.Web.UI;
using _4mvcBlog.Core;
using _4mvcBlog.Core.ViewEngine;
using System.Web.UI.WebControls;

namespace _4mvcBlog.Controllers
{
    public partial class AdminController
    {
        #region 随笔操作
        /// <summary>
        /// 显示随笔管理页面
        /// </summary>
        public ActionResult PostManage(int? id)
        {
            List<IPublishable> posts = BlogEngine.Core.Post.Posts
                .ConvertAll(new Converter<Post, IPublishable>(delegate(Post p) { return p as IPublishable; }));
            
            int pageIndex = (id != null && id.HasValue && id.Value > 0) ? id.Value : 1;
            int pageSize = 10;//Math.Min(posts.Count, BlogSettings.Instance.PostsPerPage);
            int take = pageSize;
            int total = posts.Count;
            if ((pageIndex - 1) * pageSize >= total)
            {
                return ShowMsg(new List<string>() { "页码超出范围" });
            }
            if (pageIndex * pageSize > total)
            {
                take = total - (pageIndex - 1) * pageSize;
            }
            posts = posts.GetRange((pageIndex - 1) * pageSize, take);

            return View(posts.ToPagedList<IPublishable>(pageIndex, pageSize, total));
        }

        #region 添加随笔. 保存时使用ModelBinder
        /// <summary>
        /// 显示发表新随笔页面
        /// </summary>
        [AcceptVerbs("GET")]
        public ActionResult NewPost()
        {
            InitCategorysViewData(null);
            ValueProviderResult vpr = new ValueProviderResult("", "", System.Globalization.CultureInfo.CurrentCulture);
            ModelState msTags = new ModelState() { Value = vpr };
            ///用于绑定到Html.TextBox("Tags")的值.绑定时会先从ModelState中取值.
            ViewData.ModelState.Add("Tags", msTags);
            return View();
        }
        /// <summary>
        /// 将提交过来的新随笔表单内容保存到数据库.
        /// 这里使用ModelBinder
        /// </summary>
        [AcceptVerbs("POST"), ActionName("NewPost")]
        [TestUserAuthorize]
        public ActionResult SaveNewPost(Post post)
        {
            if (!post.IsValid)
            {
                foreach (string key in post.BrokenRules.Keys)
                {
                    ViewData.ModelState.AddModelError(key, post.BrokenRules[key]);
                    //ViewData.ModelState.AddModelError(key, form[key], post.BrokenRules[key]);
                }
                InitCategorysViewData(Request.Form["Categories"]);
                return View(post);
            }

            post.Author = this.User.Identity.Name;
            post.Save();
            return ShowMsg("发表新随笔成功");
        }
        #endregion

        #region 编辑随笔.使用UpdateModel
        /// <summary>
        /// 显示编辑随笔页面。
        /// </summary>
        public ActionResult EditPost(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return ShowMsg("请指定要编辑的Post的ID");
            }

            Post post = Post.GetPost(new Guid(id));

            ValueProviderResult vpr = new ValueProviderResult(string.Join(",", post.Tags.ToArray()), string.Join(",", post.Tags.ToArray()), System.Globalization.CultureInfo.CurrentCulture);
            ModelState msTags = new ModelState() { Value = vpr };// { AttemptedValue = string.Join(",", post.Tags.ToArray()) };
            ///用于绑定到Html.TextBox("Tags")的值.绑定时会先从ModelState中取值.
            ViewData.ModelState.Add("Tags", msTags);

            string categoryIds = "";
            foreach (Category c in post.Categories)
            {
                categoryIds += string.IsNullOrEmpty(categoryIds) ? c.Id.ToString() : "," + c.Id.ToString();
            }
            InitCategorysViewData(categoryIds);

            return View(post);
        }

        /// <summary>
        /// 更新随笔到数据库.
        /// 使用UpdateModel。
        /// </summary>
        [TestUserAuthorize]
        public ActionResult UpdataPost(string id, FormCollection form)
        {
            if (string.IsNullOrEmpty(id))
            {
                return ShowMsg("请指定要更新的Post的ID");
            }

            Post post = Post.GetPost(new Guid(id));
            string categoryIds = form["Categories"] ?? "";
            try
            {
                //UpdateModel(post, new[] { "Title", "Content", "Slug", "Tags", "Categories" }, new PostValueProvider(ControllerContext));
                UpdateModel(post, new[] { "Title", "Content", "Slug", "Tags", "Categories", "IsPublished", "IsCommentsEnabled", "Description" },
                    PostValueProvider.GetValueProvider(ControllerContext));
            }
            catch
            {
                InitCategorysViewData(categoryIds);
                return View(post);
            }

            if (!post.IsValid)
            {
                foreach (string key in post.BrokenRules.Keys)
                {
                    ViewData.ModelState.AddModelError(key, post.BrokenRules[key]);
                }
                InitCategorysViewData(categoryIds);
                return View(post);
            }

            post.Save();
            return ShowMsg(new List<string>() { "编辑随笔成功" });
        }
        #endregion

        #region 删除随笔
        /// <summary>
        /// 删除随笔
        /// </summary>
        [TestUserAuthorize]
        public ActionResult DelPost(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return ShowMsg(new List<string>() { "请指定要查看的Post的Id" });
            }
            try
            {
                Guid guid = new Guid(id);
                BlogEngine.Core.Post post = BlogEngine.Core.Post.GetPost(guid);
                post.Delete();
                post.Save();
                return ShowMsg(new List<string>() { "删除随笔《" + post.Title + "》成功" });
            }
            catch (Exception ex)
            {
                return ShowMsg(new List<string>() { ex.Message });
            }
        }
        #endregion

        #endregion
    }
}
